<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px" class="header-search">
      <el-form-item label="消息类型" prop="messageType">
        <el-select v-model="queryParams.messageType" placeholder="请输入" clearable style="width: 220px;">
          <el-option
            v-for="dict in message_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="接收时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 320px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 顶部筛选与操作条（保持原四个按钮不动） -->
    <div class="toolbar-row">
      <div class="left-group">
        <!-- 状态筛选：未读 / 已读（附带数量） -->
        <el-button-group>
          <el-button :type="queryParams.status === 0 ? 'primary' : 'default'" @click="filterByStatus(0)">未读 {{ unreadCount }}</el-button>
          <el-button :type="queryParams.status === 1 ? 'primary' : 'default'" @click="filterByStatus(1)">已读 {{ readCount }}</el-button>
        </el-button-group>
      </div>
      <div class="right-group">
        <!-- 额外 删除（与多选删除一致，不影响上方四个按钮） -->
        <el-button :disabled="multiple" @click="handleDelete()">删除</el-button>
        <!-- 标记为已读 -->
        <el-button :type="markReadButtonType" :disabled="!canMarkSelectedAsRead" @click="markSelectedAsRead">标记为已读</el-button>
        <!-- 全部已读 -->
        <el-button type="primary" plain @click="markAllAsRead">全部已读</el-button>
        <!-- 全部删除 -->
        <el-button type="danger" plain @click="deleteAll">全部删除</el-button>
      </div>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:messagecenter:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:messagecenter:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:messagecenter:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:messagecenter:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="messagecenterList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="消息标题" align="center" prop="title" />
      <el-table-column label="消息内容" align="center" prop="content" />
      <el-table-column label="接收时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="消息类型" align="center" prop="messageType">
        <template #default="scope">
          <dict-tag :options="message_type" :value="scope.row.messageType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:messagecenter:edit']">修改</el按钮> -->
          <el-button link type="primary"  @click="handleDelete(scope.row)" >删除</el-button>
          <el-button link type="primary"  @click="handleView(scope.row)" >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改消息通知对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="messagecenterRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入消息标题" />
        </el-form-item>
        <el-form-item label="消息内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="消息类型" prop="messageType">
          <el-select v-model="form.messageType" placeholder="请选择消息类型">
            <el-option
              v-for="dict in message_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息接收人编号" prop="receiverId">
          <el-input v-model="form.receiverId" placeholder="请输入消息接收人编号" />
        </el-form-item>
        <el-form-item label="额外字段1" prop="extraField1">
          <el-input v-model="form.extraField1" placeholder="请输入额外字段1" />
        </el-form-item>
        <el-form-item label="额外字段2" prop="extraField2">
          <el-input v-model="form.extraField2" placeholder="请输入额外字段2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看消息通知对话框 -->
    <el-dialog title="查看消息" v-model="viewOpen" width="600px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="消息标题">{{ viewData.title }}</el-descriptions-item>
        <el-descriptions-item label="消息内容">
          <div v-html="viewData.content"></div>
        </el-descriptions-item>
        <el-descriptions-item label="消息类型">
          <dict-tag :options="message_type" :value="viewData.messageType"/>
        </el-descriptions-item>
        <el-descriptions-item label="接收时间">{{ parseTime(viewData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ viewData.status === 0 ? '未读' : '已读' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Messagecenter">
import { listMessagecenter, getMessagecenter, delMessagecenter, addMessagecenter, updateMessagecenter } from "@/api/system/messagecenter"

const { proxy } = getCurrentInstance()
const { message_type } = proxy.useDict('message_type')

const messagecenterList = ref([])
const open = ref(false)
const viewOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const unreadCount = ref(0)
const readCount = ref(0)
const viewData = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    title: null,
    content: null,
    createTime: null,
    messageType: null,
    receiverId: null,
    status: null,
    extraField1: null,
    extraField2: null
  },
  rules: {
    title: [
      { required: true, message: "消息标题不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "接收时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询消息通知列表 */
function getList() {
  loading.value = true
  listMessagecenter(queryParams.value).then(response => {
    messagecenterList.value = response.rows
    total.value = response.total
    loading.value = false
    // 同步刷新未读/已读数量
    refreshCounts()
  })
}

// 根据状态筛选
function filterByStatus(status) {
  queryParams.value.status = status
  queryParams.value.pageNum = 1
  getList()
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    content: null,
    createTime: null,
    messageType: null,
    receiverId: null,
    status: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("messagecenterRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
  // 统计所选中项的未读/已读情况
  const selected = selection
  const hasUnread = selected.some(s => s.status === 0)
  const hasRead = selected.some(s => s.status === 1)
  canMarkSelectedAsRead.value = hasUnread
  markReadButtonType.value = hasUnread ? (hasRead ? 'primary' : 'primary') : 'default'
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加消息通知"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMessagecenter(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改消息通知"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["messagecenterRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMessagecenter(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMessagecenter(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除消息通知编号为"' + _ids + '"的数据项？').then(function() {
    return delMessagecenter(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
    // 通知顶部导航刷新未读红点
    window.dispatchEvent(new Event('unread-refresh'))
  }).catch(() => {})
}

// 查看详情并在未读时标记为已读
function handleView(row) {
  const id = row.id
  getMessagecenter(id).then(response => {
    const detail = response.data || {}
    viewData.value = detail
    viewOpen.value = true
    // 若未读则标记为已读
    if (row.status === 0) {
      updateMessagecenter({ ...detail, status: 1 }).then(() => {
        // 刷新列表和数量
        getList()
        // 通知顶部导航刷新未读红点
        window.dispatchEvent(new Event('unread-refresh'))
      })
    }
  })
}

// 标记为已读（选中项）
const canMarkSelectedAsRead = ref(false)
const markReadButtonType = ref('default')
function markSelectedAsRead() {
  if (!ids.value.length) return
  // 只更新未读的数据
  const needUpdate = messagecenterList.value.filter(item => ids.value.includes(item.id) && item.status === 0)
  if (!needUpdate.length) return
  const reqs = needUpdate.map(item => updateMessagecenter({ ...item, status: 1 }))
  Promise.all(reqs).then(() => {
    proxy.$modal.msgSuccess('已标记为已读')
    getList()
    // 通知顶部导航刷新未读红点
    window.dispatchEvent(new Event('unread-refresh'))
  })
}

// 全部已读
function markAllAsRead() {
  if (!messagecenterList.value.length) return
  const needUpdate = messagecenterList.value.filter(item => item.status === 0)
  if (!needUpdate.length) {
    proxy.$modal.msgSuccess('已全部为已读')
    return
  }
  const reqs = needUpdate.map(item => updateMessagecenter({ ...item, status: 1 }))
  Promise.all(reqs).then(() => {
    proxy.$modal.msgSuccess('全部标记为已读')
    getList()
    window.dispatchEvent(new Event('unread-refresh'))
  })
}

// 全部删除
function deleteAll() {
  if (!messagecenterList.value.length) return
  proxy.$modal.confirm('确定删除全部消息吗？').then(() => {
    const reqs = messagecenterList.value.map(item => delMessagecenter(item.id))
    return Promise.all(reqs)
  }).then(() => {
    proxy.$modal.msgSuccess('已删除全部消息')
    getList()
    window.dispatchEvent(new Event('unread-refresh'))
  }).catch(() => {})
}

// 刷新未读/已读数量
function refreshCounts() {
  const base = { ...queryParams.value }
  // 未读
  listMessagecenter({ ...base, pageNum: 1, pageSize: 1, status: 0 }).then(res => {
    unreadCount.value = res.total || 0
  })
  // 已读
  listMessagecenter({ ...base, pageNum: 1, pageSize: 1, status: 1 }).then(res => {
    readCount.value = res.total || 0
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/messagecenter/export', {
    ...queryParams.value
  }, `messagecenter_${new Date().getTime()}.xlsx`)
}

// 初始默认展示未读
queryParams.value.status = 0
getList()
</script>

<style scoped>
.toolbar-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.left-group {
  display: flex;
  gap: 8px;
}
.right-group {
  display: flex;
  gap: 8px;
}
.header-search {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}
.header-search .el-form-item {
  margin-right: 16px;
}
</style>
